<?php

namespace common\models;

use Yii;
use yii\helpers\Json;
use common\helpers\Url;
use common\helpers\IpHelper;

/**
 * This is the model class for table "{{%attachment}}".
 *
 * @property int $id
 * @property int $user_id 用户ID
 * @property string $path 保存路径
 * @property string $original_name 原始名称
 * @property string $size 文件大小（单位：字节）
 * @property string $channel 远端上传通道
 * @property int $isimage 是否图片
 * @property int $width 宽度
 * @property int $height 高度
 * @property int $download 浏览或者下载次数
 * @property int $ip 上传IP地址
 * @property string $auth_token 校验Token
 * @property int $site_id 来源站点ID
 * @property int $status 附件状态
 * @property int $created_at
 * @property int $updated_at
 */
class Attachment extends \common\db\ActiveRecord {

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%attachment}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['user_id', 'size', 'isimage', 'width', 'height', 'download', 'ip', 'site_id', 'status', 'created_at', 'updated_at'], 'integer'],
            [['path', 'original_name', 'auth_token'], 'required'],
            [['path', 'original_name'], 'string', 'max' => 255],
            [['channel'], 'string', 'max' => 20],
            [['auth_token'], 'string', 'max' => 32],
            [['path'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'user_id' => '用户ID',
            'path' => '保存路径',
            'original_name' => '原始名称',
            'size' => '文件大小（单位：字节）',
            'channel' => '远端上传通道',
            'isimage' => '是否图片',
            'width' => '宽度',
            'height' => '高度',
            'download' => '浏览或者下载次数',
            'ip' => '上传IP地址',
            'auth_token' => '校验Token',
            'site_id' => '来源站点ID',
            'status' => '附件状态',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }

    public function setToken() {
        $this->auth_token = md5(Json::encode($this->attributes));
    }

    public function fields() {
        return [
            'id',
            'user_id',
            'path',
            'url' => function() {
                return Url::attach($this->path);
            },
            'size',
            'channel',
            'isimage',
            'width',
            'height',
            'download',
            'ip' => function() {
                return IpHelper::long2ip($this->ip);
            },
        ];
    }

    public function afterSave($insert, $changedAttributes) {
        parent::afterSave($insert, $changedAttributes);
        if ($this->channel == 'OSS') {
            $path = ltrim($this->path, '/');
            Yii::$app->alioss->putObjectACL(ltrim($this->path, '/'), 'public-read');
        }
    }

}
